Object.defineProperty(exports, "__esModule", { value: true });
const fs = require('fs')
const chalk = require('chalk')
const path = require('path');
const { preview, Project, upload } = require('miniprogram-ci');
const { getFormatFileSize, getPackageName } = require('./util');
let QrType = 'base64' || 'image' || 'terminal';

let Options = {
  workspace: "",
  env: "",
  version: "",
  desc: "",
  pkp: "",
  type: '',
  qr: QrType,
  qrDest: "",
  robot: ''
}

let ProjectConfig = {
  appid: "",
  miniprogramRoot: "",
  setting: '',
  compileType: "",
}

let UploadOptions = {
  proxy: ""
}

let PreviewOptions = {
  qr: QrType,
  qrDest: "",
  proxy: "",
  pagePath: "",
  searchQuery: "",
}

function fsExistsSync(path) {
  try {
    // @ts-ignore
    fs.accessSync(path, fs.F_OK);
  } catch (e) {
    return false;
  }
  return true;
}


class Ci {

  constructor(opts) {
    const { workspace, type, version, desc, pkp, env, robot } = opts;
    this.workspace = workspace;
    this.version = version;
    this.desc = desc;
    this.env = env;
    this.robot = robot;
    // 加载配置文件
    if (this.loadProjectConfig(path.join(workspace, 'project.config.json')) && this.projectConfig) {
      this.project = new Project({
        appid: this.projectConfig.appid,
        type: type,
        projectPath: workspace,
        privateKeyPath: pkp,
        ignores: ['node_modules/**/*'],
      });
    }
  }

  loadProjectConfig(configPath) {
    if (this.isFileExist(configPath)) {
      try {
        const jsonString = fs.readFileSync(configPath);
        const config = JSON.parse(jsonString.toString());
        this.projectConfig = {
          appid: config.appid,
          miniprogramRoot: config.miniprogramRoot,
          setting: config.setting,
          compileType: config.compileType,
        };
        return true;
      } catch (error) {
        console.log(chalk.red('Load file failed'));
        console.log(chalk.red(error));
        return false;
      }
    }
    return false;
  }

  isFileExist(file) {
    return fsExistsSync(file);
  }

  async getTitleFromGit() {
    let version = this.version || process.env.npm_package_version || '';
    let desc = this.desc;
    let envDesc = this.env ? `env: ${this.env}` : '';
    if (!version) {
      try {
        const pkg = require(path.resolve(this.workspace, 'package.json'));
        version = pkg.version;
      } catch (error) {
        version = '0.0.0';
        console.error(chalk.red('Load package.json failed'));
        console.error(chalk.red(error));
      }
    }
    if (this.env) {
      version = `${version}.${this.env}`;
    }
    desc = `${envDesc} ${this.desc}`;
    return {
      version,
      desc,
    };
  }

  printResult(version, desc, result = {}) {
    const { subPackageInfo = [], pluginInfo = [], devPluginId = '无' } = result;    
    subPackageInfo.forEach(packageInfo => {
      const formatSize = getFormatFileSize(packageInfo.size);
      packageTable.push([getPackageName(packageInfo.name), formatSize.size + formatSize.measure]);
    });
    console.log(packageTable.toString());
    if (pluginInfo && pluginInfo.length) {
      console.log('插件信息');
      pluginInfo.forEach(pluginInfo => {
        const formatSize = getFormatFileSize(pluginInfo.size);
        pluginTable.push([pluginInfo.pluginProviderAppid, pluginInfo.version, formatSize.size + formatSize.measure, devPluginId]);
      });
      console.log(pluginTable.toString());
    }
  }

  relsoveQrPath(qrcodeFormat = QrType || undefined, qrcodeOutputDest = "") {
    if (qrcodeFormat === 'base64' || qrcodeFormat === 'image') {
      return path.join(this.workspace, qrcodeOutputDest || 'preview.png');
    }
    return '';
  }

  async upload(opts = UploadOptions) {
    if (this.project) {
      const info = await this.getTitleFromGit();
      console.log('上传...')
      try {
        const uploadResult = await upload({
          project: this.project,
          version: info.version,
          desc: info.desc,
          setting: this.projectConfig ? this.projectConfig.setting : {},
          onProgressUpdate: function () { },
          proxy: opts.proxy || '',
          robot: this.robot,
        });
        console.log('上传成功', info.version, info.desc, uploadResult)
      } catch (error) {
        console.error(chalk.red(error));
        process.exit(1);
      }
    }
  }

  async preview(opts = PreviewOptions) {
    if (this.project) {
      const info = await this.getTitleFromGit();
      console.log('开始预览···')
      try {
        const previewResult = await preview({
          project: this.project,
          version: info.version,
          desc: info.desc,
          setting: this.projectConfig ? this.projectConfig.setting : {},
          qrcodeFormat: opts.qr,
          qrcodeOutputDest: this.relsoveQrPath(opts.qr, opts.qrDest),
          onProgressUpdate: function () { },
          pagePath: opts.pagePath,
          searchQuery: opts.searchQuery, // 这里的`&`字符在命令行中应写成转义字符`\&`
          // @ts-ignore
          proxy: opts.proxy || '',
          robot: this.robot,
        });
        // this.printResult(info.version, info.desc, previewResult);
        console.log('预览成功', info.version, info.desc, uploadResult)
      } catch (e) {
        console.error(chalk.red(e.message));
        process.exit(1);
      }
    }
  }
}

module.exports = Ci;

